var express = require('express');
var router = express.Router();
var connection = require("../db/connection.js");


// 获取学生
var getStudentList = function(req,res){
    var checkStudentSql = 'SELECT * FROM student'; //sql语句 (第一个参数)
    var checkParams = [];//条件 (第二个参数)
    connection.query(checkStudentSql,checkParams, function (err, data) {
        if (err) { 
            console.log(err)
            return;
        }
        res.json({
            code:0,
            data:data
        })
    });
}

// 添加学生
var addStudent = function(req,res){
    let addSql = 'INSERT INTO student(no,name,sex,birthday,class) VALUES(?,?,?,?,?)';
    let paramsArr = [];
    paramsArr[0] = req.body.no;
    paramsArr[1] = req.body.name;
    paramsArr[2] = req.body.sex;
    paramsArr[3] = req.body.birthday;
    paramsArr[4] = req.body.class;
    connection.query(addSql,paramsArr, function (err, data) {
        if (err) { 
            console.log(err)
            return;
        }
        res.json({
            code:0,
            msg:"添加成功"
        })
    });
}

// 删除学生
var deleteStudent = function(req,res){
    /** 一 */
    // var  delSql = 'DELETE FROM student WHERE no = ' + req.body.no;
    /** 二 */
    var  delSql = 'DELETE FROM student WHERE no = ?';
    var delParams = req.body.no; //条件
    connection.query(delSql,delParams, function (err, data) {
        if (err) { 
            console.log(err)
            return;
        }
        res.json({
            code:0,
            msg:"删除成功"
        })
    });
}


// 编辑学生
var editStudent = function(req,res){
    var  editSql = 'UPDATE student SET name = ?,sex = ?,birthday=?,class=? WHERE no = ?';
    var edit_params = [];
    edit_params[0] = req.body.name;
    edit_params[1] = req.body.sex;
    edit_params[2] = req.body.birthday;
    edit_params[3] = req.body.class;
    edit_params[4] = req.body.no;
    connection.query(editSql,edit_params, function (err, data) {
        if (err) { 
            console.log(err)
            return;
        }
        res.json({
            code:0,
            msg:"编辑成功"
        })
    });
}

module.exports = {
    getStudentList,
    addStudent,
    deleteStudent,
    editStudent
};
